const { app, BrowserWindow, ipcMain, dialog, shell } = require('electron');
const path = require('path');
const fs = require('fs');
const isDev = require('electron-is-dev');
const { promisify } = require('util');
const { scanPrefabFiles, saveScanResults } = require('./prefab-scanner');

// Disable GPU acceleration before app is ready
app.disableHardwareAcceleration();

let mainWindow;

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      webSecurity: false,
      allowRunningInsecureContent: true,
      devTools: true
    }
  });

  mainWindow.loadURL(
    isDev
      ? 'http://localhost:5173'
      : `file://${path.join(__dirname, '../dist/index.html')}`
  );

  if (isDev) {
    // 设置 DevTools 选项
    mainWindow.webContents.session.clearCache();
    mainWindow.webContents.session.clearStorageData();
    mainWindow.webContents.openDevTools({ mode: 'detach' });
  }
}

app.whenReady().then(createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

// Handle folder selection
ipcMain.handle('select-folder', async () => {
  const result = await dialog.showOpenDialog(mainWindow, {
    properties: ['openDirectory']
  });
  return result.filePaths[0];
});

// Scan directory for files
ipcMain.handle('scan-directory', async (event, dirPath) => {
  console.log('开始扫描目录:', dirPath);

  // 检查目录中的图片文件
  function analyzeImageFiles(files) {
    const result = {
      imageCount: 0,
      imageFiles: new Set(),
      shouldCheckImages: new Set()
    };

    // 1. 先找出所有配置文件和它们引用的图片
    const configFiles = new Set();
    const fntImages = new Set();  // 存储.fnt文件引用的图片
    const imageFiles = new Set();

    // 第一遍：收集所有配置文件和图片
    for (const [fileName, filePath] of files) {
      const ext = path.extname(fileName).toLowerCase();
      const baseName = path.basename(fileName, ext);
      
      if (ext === '.fnt') {
        configFiles.add(baseName);
        console.log('找到配置文件:', fileName, '基础名:', baseName);
        // 读取.fnt文件内容
        try {
          const content = fs.readFileSync(filePath, 'utf8');
          // 使用简单的正则表达式匹配page标签中的file属性
          const match = content.match(/file="([^"]+)"/);
          if (match) {
            const referencedImage = match[1];
            fntImages.add(referencedImage);
            console.log('字体文件引用的图片:', referencedImage);
          }
        } catch (err) {
          console.error('读取.fnt文件时出错:', err);
        }
      } else if (ext === '.plist') {
        configFiles.add(baseName);
        console.log('找到配置文件:', fileName, '基础名:', baseName);
      } else if (['.png', '.jpg', '.jpeg', '.gif'].includes(ext)) {
        imageFiles.add({
          fileName,
          baseName: path.basename(fileName, ext)
        });
        console.log('找到图片文件:', fileName, '基础名:', path.basename(fileName, ext));
      }
    }

    console.log('文件分析:', {
      configFiles: Array.from(configFiles),
      fntImages: Array.from(fntImages),
      imageFiles: Array.from(imageFiles).map(f => f.fileName)
    });

    // 2. 检查每个图片文件
    for (const imageInfo of imageFiles) {
      // 检查是否是配置文件的配套图片
      const isConfigImage = configFiles.has(imageInfo.baseName) || // 完全匹配
                          fntImages.has(imageInfo.fileName);    // 检查是否是.fnt文件引用的图片

      if (isConfigImage) {
        console.log('跳过配置文件的配套图片:', imageInfo.fileName, '基础名:', imageInfo.baseName);
        continue;
      }

      // 这是一个散图
      console.log('找到散图:', imageInfo.fileName);
      result.imageFiles.add(imageInfo.fileName);
      result.imageCount++;
      result.shouldCheckImages.add(imageInfo.fileName);
    }

    if (result.shouldCheckImages.size > 0) {
      console.log('最终需要检查的图片文件列表:', Array.from(result.shouldCheckImages));
    }

    return result;
  }

  // 检查目录中的 pac 文件
  function checkPacFile(files) {
    for (const [fileName, filePath] of files) {
      const ext = path.extname(fileName).toLowerCase();
      if (ext === '.pac') {
        console.log('找到pac文件:', fileName);
        return true;
      }
    }
    return false;
  }

  // 递归扫描目录
  function scanDir(currentPath, parentHasPac = false) {
    try {
      console.log('\n=== 开始扫描目录 ===');
      console.log('当前目录:', currentPath);
      console.log('父目录是否有pac:', parentHasPac);

      const result = {
        path: currentPath,
        name: path.basename(currentPath),
        children: [],
        hasImages: false,
        hasAtlas: parentHasPac, // 只有当父目录有.pac文件时才继承
        shouldCheck: false,
        abnormalCount: 0  // 添加异常目录计数
      };

      // 收集当前目录中的所有文件和子目录
      const items = fs.readdirSync(currentPath);
      console.log('目录内容:', items);

      // 分离文件和目录
      const files = new Map();
      const subdirs = new Map();

      for (const item of items) {
        try {
          const fullPath = path.join(currentPath, item);
          const stats = fs.statSync(fullPath);

          if (stats.isDirectory()) {
            console.log('找到子目录:', item);
            subdirs.set(item, fullPath);
          } else {
            console.log('找到文件:', item);
            files.set(item, fullPath);
          }
        } catch (itemErr) {
          console.error('处理文件/目录时出错:', item, itemErr);
        }
      }

      // 检查当前目录是否有 pac 文件
      const hasPac = checkPacFile(files);
      const currentHasAtlas = parentHasPac || hasPac; // 计算当前目录的hasAtlas状态
      result.hasAtlas = currentHasAtlas;
      console.log('当前目录是否有pac:', result.hasAtlas, '(父目录继承:', parentHasPac, '当前目录:', hasPac, ')');

      // 先分析当前目录的文件
      const imageAnalysis = analyzeImageFiles(files);
      console.log('当前目录图片分析结果:', {
        path: currentPath,
        imageCount: imageAnalysis.imageCount,
        imageFiles: Array.from(imageAnalysis.imageFiles),
        shouldCheckImages: Array.from(imageAnalysis.shouldCheckImages),
        hasAtlas: result.hasAtlas
      });

      // 更新当前目录的状态
      if (imageAnalysis.imageCount === 0) {
        console.log('当前目录没有图片文件');
        result.hasImages = false;
        result.shouldCheck = false;
      } else if (imageAnalysis.shouldCheckImages.size === 0) {
        console.log('当前目录的图片都不需要检查');
        result.hasImages = true;  // 有图片，但都是配置文件的配套图片
        result.shouldCheck = false;
      } else if (imageAnalysis.shouldCheckImages.size === 1) {
        console.log('当前目录只有一个散图，不需要检查');
        result.hasImages = true;
        result.shouldCheck = false;
      } else {
        console.log('当前目录有多个需要检查的图片:', imageAnalysis.shouldCheckImages.size, '个');
        result.hasImages = true;
        result.shouldCheck = !currentHasAtlas; // 使用当前计算的hasAtlas状态
        console.log('目录是否需要检查:', result.shouldCheck, '(hasAtlas:', currentHasAtlas, ')');
      }

      // 如果当前目录需要检查，增加异常计数
      if (result.shouldCheck) {
        result.abnormalCount = 1; // 直接设置为1，不累加
        console.log('当前目录标记为异常');
      }

      // 然后处理子目录，传递当前目录的.pac状态
      for (const [dirName, dirPath] of subdirs) {
        try {
          console.log('\n--- 处理子目录:', dirName, '---');
          const childResult = scanDir(dirPath, currentHasAtlas); // 传递当前的hasAtlas状态给子目录
          if (childResult) {
            result.children.push(childResult);
            // 更新当前目录的状态
            result.hasImages = result.hasImages || childResult.hasImages;
            // 不需要更新hasAtlas，因为它已经在之前设置好了
            console.log('子目录处理完成');
          }
        } catch (err) {
          console.error('处理子目录时出错:', dirName, err);
        }
      }

      console.log('\n=== 目录扫描完成 ===');
      console.log('目录:', currentPath);
      console.log('结果:', {
        hasImages: result.hasImages,
        hasAtlas: result.hasAtlas,
        shouldCheck: result.shouldCheck,
        childrenCount: result.children.length,
        abnormalCount: result.abnormalCount
      });

      return result;
    } catch (err) {
      console.error('扫描目录时出错:', currentPath, err);
      return null;
    }
  }

  try {
    if (!fs.existsSync(dirPath)) {
      throw new Error('目录不存在: ' + dirPath);
    }

    const stats = fs.statSync(dirPath);
    if (!stats.isDirectory()) {
      throw new Error('所选路径不是目录: ' + dirPath);
    }

    const result = scanDir(dirPath);
    if (!result) {
      throw new Error('扫描目录失败: ' + dirPath);
    }

    console.log('完整扫描结果:', JSON.stringify(result, null, 2));
    return result;
  } catch (error) {
    console.error('扫描过程出错:', error);
    throw error;
  }
});

// Handle opening path in system file explorer
ipcMain.handle('open-path', async (event, path) => {
  await shell.openPath(path);
});

// Check for .pac with .fnt or .plist combinations
ipcMain.handle('check-file-combinations', async (event, dirPath) => {
  try {
    // 递归读取目录中的所有文件
    function getAllFiles(dir) {
      let results = [];
      const items = fs.readdirSync(dir);
      
      for (const item of items) {
        const fullPath = path.join(dir, item);
        const stat = fs.statSync(fullPath);
        
        if (stat.isDirectory()) {
          results = results.concat(getAllFiles(fullPath));
        } else {
          results.push({
            name: item,
            path: fullPath,
            ext: path.extname(item).toLowerCase()
          });
        }
      }
      
      return results;
    }

    console.log('开始扫描目录:', dirPath);
    const allFiles = getAllFiles(dirPath);
    console.log('找到文件数量:', allFiles.length);

    // 按目录分组文件
    const filesByDir = allFiles.reduce((acc, file) => {
      const dir = path.dirname(file.path);
      if (!acc[dir]) {
        acc[dir] = [];
      }
      acc[dir].push(file);
      return acc;
    }, {});

    // 检查每个目录
    const results = [];
    for (const [dir, files] of Object.entries(filesByDir)) {
      const hasPac = files.some(file => file.ext === '.pac');
      const hasPlist = files.some(file => file.ext === '.plist');

      if ( (hasPac && hasPlist)) {
        results.push({
          directory: dir,
          hasPacPlist: hasPac && hasPlist,
          details: {
            hasPac,
            hasPlist
          }
        });
      }
    }

    console.log('检查结果:', results);

    return {
      directories: results,
      summary: {
        totalDirs: Object.keys(filesByDir).length,
        matchingDirs: results.length
      }
    };
  } catch (error) {
    console.error('检查文件组合时出错:', error);
    throw error;
  }
});

// 在现有IPC handlers后修改prefab扫描handler
ipcMain.handle('scan-prefab-files', async (event, dirPath) => {
  try {
    const result = await scanPrefabFiles(dirPath);
    return result;
  } catch (error) {
    console.error('扫描prefab文件时出错:', error);
    throw error;
  }
});

// 添加导出扫描结果的处理程序
ipcMain.handle('save-prefab-scan-results', async (event, results) => {
  try {
    // 打开保存对话框
    const { canceled, filePath } = await dialog.showSaveDialog({
      title: '保存扫描结果',
      defaultPath: path.join(app.getPath('desktop'), 'particle-system-scan-result.json'),
      filters: [
        { name: 'JSON Files', extensions: ['json'] }
      ]
    });

    if (canceled || !filePath) {
      return { success: false, message: '用户取消了保存操作' };
    }

    // 保存文件
    console.log('准备保存文件到:', filePath);
    console.log('结果数据类型:', typeof results);
    await saveScanResults(results, filePath);
    return { success: true, filePath };
  } catch (error) {
    console.error('保存扫描结果时出错:', error);
    throw error;
  }
});